package net.ezsteam.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.ezsteam.EzSteam_StoreVisit_Activity;
import net.ezsteam.R;
import net.ezsteam.cons.EzSteam_Urls;
import net.ezsteam.object.EzSteam_Checked_Car;
import net.ezsteam.service.EzSteam_GetCars_Service.MyAdapter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;


public class EzSteam_Clean_Type extends AsyncTask<String, Void, String> {

	private ProgressDialog progdialod;
	private Activity activity;
	private Context context;
	
	private boolean exeption = false;
	
	private Spinner spn;
	
	
	// connection establish timeout (timeoutConnection)
	private int timeoutConnection = 5000;
	// socket timeout (timeoutSocket) 
	private int timeoutSocket = 45000;

	JSONArray jArray;
	
	String[] defaults;
	
	String[] typeid;
	
	String[] arrAllCars;
	String[] arrAppCars;
	
	String theOne="";
	
	static InputStream is = null;
	static JSONObject jobj = null;
	static String json = ""; 
	List<NameValuePair> params;
	HttpParams httpParameters = new BasicHttpParams();

	
	public EzSteam_Clean_Type(Activity activity,Spinner spn) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.spn = spn;
		
	}
	
	public EzSteam_Clean_Type(Activity activity,Spinner spn,String[] defaults,String[] arrAppCars,String[] arrAllCars,String theOne) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.spn = spn;
		this.defaults = new String[defaults.length];
		this.defaults = defaults;
		this.arrAllCars = new String[arrAllCars.length];
		this.arrAllCars = arrAllCars;
		this.arrAppCars = new String[arrAppCars.length];
		this.arrAppCars = arrAppCars;
		this.theOne = theOne;
		
	}
	
	public EzSteam_Clean_Type(Activity activity,Spinner spn,String[] arrAllCars) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.spn = spn;
		this.arrAllCars = new String[arrAllCars.length];
		this.arrAllCars = arrAllCars;
		
	}
	
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progdialod = ProgressDialog.show(this.activity, "Clean Types", "Loading Clean types, Please Wait",true,false);
	}
	
	
	@Override
	protected String doInBackground(String... urls) {

		try {
			
			HttpClient httpclient = new DefaultHttpClient();
		    HttpResponse response = httpclient.execute(new HttpGet(urls[0]));
		    
			HttpEntity httpEntity = response.getEntity();

			is = httpEntity.getContent();
			
			}catch (UnsupportedEncodingException e) {
				exeption = true;
				e.printStackTrace();
			}catch (ClientProtocolException e) {
				exeption = true;
				e.printStackTrace();
			} catch (IOException e) {   
				exeption = true;
				e.printStackTrace();
			} catch (IllegalStateException e) {
				exeption = true;
				e.printStackTrace();
			} catch (Exception e) {
				exeption = true;
				e.printStackTrace();
			}
			
			try{
				BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb=new StringBuilder();
				
				String line=null;
				
				while((line=reader.readLine())!=null){
					//sb.append(line+"n");
					sb.append(line);
				}
				is.close();
				json=sb.toString();
				
				Log.e("JSON RES:",json);
				
			}catch(Exception e){
				exeption = true;
				Log.e("Buffer Error","Error converting result"+e.toString());
			}
		 return json;
		
	}
	
	@Override
	protected void onPostExecute(String result) {
		
		Log.d("Post Exec", "POST EXEC");
		
		Log.d("Post tt", result);
		progdialod.dismiss();

		
		Log.d("Post Exec", result); //"result" is the token *if not null
		
		
			if(!exeption){
				
				try {

					List<String> list = new ArrayList<String>();
					
					JSONObject jsonobj = new JSONObject(result);
					JSONArray service_type = jsonobj.getJSONArray("clean_types");
					
					typeid = new String[service_type.length()];

					for(int typei=0;typei<service_type.length();typei++){
						if(service_type.get(typei) instanceof JSONObject){
							JSONObject jsonDetails = service_type.getJSONObject(typei);
							list.add(jsonDetails.getString("id")+": "+jsonDetails.getString("type_name")+" "+jsonDetails.getString("name")+" $"+jsonDetails.getString("price"));
							typeid[typei] = jsonDetails.getString("id");
						}
					}

					String[] typeArr = new String[list.size()];
					typeArr = list.toArray(typeArr);
					
					if(typeArr.length != 0){
						ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(context, R.layout.ezsteam_spinner_item, typeArr); 
				        spinnerArrayAdapter.setDropDownViewResource(R.layout.ezsteam_spinner_item);
				        spn.setAdapter(spinnerArrayAdapter);
				        
				        
				        if(arrAppCars!=null){
					        for(int loop=0;loop<arrAppCars.length;loop++){
					        	Log.i("arrAppCars[loop]", ""+arrAppCars[loop]);
					        	if (Arrays.asList(arrAllCars).contains(arrAppCars[loop])) {
					        		Log.i("defaults[loop]", ""+defaults[loop]);
					        		Log.i("(Integer.parseInt(defaults[loop]))-1", ""+((Integer.parseInt(defaults[loop]))-1));
					        		
					        		//spn.setSelection((Integer.parseInt(defaults[loop]))-1);
					        		
					        		if (Arrays.asList(typeid).contains(defaults[loop]) && theOne.equals(arrAppCars[loop])) {
					        			spn.setSelection(Arrays.asList(typeid).indexOf(defaults[loop]));
					        		}
					        		
						        }
					        }
				        }
				        
					}
					
					
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				
				
				
			
			}else{
				Toast toast = Toast.makeText(activity, "Login Failed !!", Toast.LENGTH_SHORT);
				toast.show();
			}

	}

	

}
